import { createRouter, createWebHistory } from 'vue-router';
import HomeView from '../views/HomeView.vue';
import store from '@/store/index.js';

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      component: () => import('@/views/qinlv_home.vue'),
      meta: { requiresAuth: true, roles: ['admin', 'submitter'] }
    },
    {
      path: '/role-setting',
      component: () => import('@/views/qinlv_role.vue'),
      meta: { requiresAuth: true, roles: ['submitter','submitter' ] }
    },
    {
      path: '/notebook-creation',
      component: () => import('@/views/qinlv_create.vue'),
      meta: { requiresAuth: true, roles: ['submitter','admin'] }
    },
    {
      path: '/notebook-history',
      component: () => import('@/views/qinlv_history.vue'),
      meta: { requiresAuth: true, roles: ['submitter','admin'] }
    },
    {
      path: '/qa-management',
      component: () => import('@/views/qinlv_qa_show.vue'),
      meta: { requiresAuth: true, roles: ['admin'] }
    },
    {
      path: '/user-info',
      name: 'UserInfo',
      component: () => import('@/views/UserInfo.vue'),
      meta: { requiresAuth: true, roles: ['submitter','admin'] }
    },
    {
      path: '/scenic-management',
      name: 'scenicmanagement',
      component: () => import('@/views/qinliv_jinqu.vue'),
      meta: { requiresAuth: true, roles: ['admin'] }
    },
    {
      path: '/admin-management',
      name: 'adminmanagement',
      component: () => import('@/views/qinlv_admin.vue'),
      meta: { requiresAuth: true, roles: ['admin'] }
    },
    {
      path: '/login',
      name: 'login',
      component: () => import('@/views/LoginSwitch.vue'),
      meta: { requiresAuth: false, roles: [] }
    },
    {
      path: '/workflow',
      name: 'workflow',
      component: () => import('@/views/workflow.vue'),
      meta: { requiresAuth: true, roles: ['submitter']}
    },
    {
      path: '/know',
      name: 'know',
      component: () => import('@/views/know.vue'),
      meta: { requiresAuth: true, roles: ['submitter','admin']}
    },
    {
      path: '/user',
      name: 'user',
      component: () => import('@/views/user.vue'),
      meta: { requiresAuth: true, roles: ['admin']}
    },
    {
      path: '/workflow1',
      name: 'workflow1',
      component: () => import('@/views/workflow1.vue'),
      meta: { requiresAuth: true, roles: ['admin']}
    },
  ]
});

router.beforeEach((to, from, next) => {
  const isAuthenticated = store.state.isAuthenticated;
  const userRole = store.state.userRole;
  const requiresAuth = to.matched.some(record => record.meta.requiresAuth);
  const allowedRoles = to.matched.some(record => record.meta.roles.includes(userRole));

  if (requiresAuth && !isAuthenticated) {
    next({ name: 'login' });
  } else if (requiresAuth && !allowedRoles) {
    next({ path: '/' });
  } else {
    next();
  }
});

export default router;
